<template>
    <div class="forum-container">
        <!-- 头部操作栏 -->
        <div class="forum-header">
            <!-- 搜索框 -->
            <div class="search-container">
                <el-input v-model="param.title" placeholder="搜索帖子..." class="search-input" clearable size="large">
                    <template #append>
                        <el-button @click="loadPosts" type="primary" icon="el-icon-search" class="search-btn" />
                    </template>
                </el-input>
            </div>

            <!-- 发帖按钮 -->
            <el-button type="primary" @click="openPostDialog" class="create-btn" size="large">
                <i class="el-icon-edit"></i>
                发帖
            </el-button>
        </div>

        <!-- 帖子列表 -->
        <div class="post-grid">
            <el-card v-for="post in posts" :key="post.id" class="post-card" shadow="hover">
                <div class="card-header">
                    <el-avatar :size="40"
                        :src="post.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
                        class="user-avatar" />
                    <div class="post-meta">
                        <div class="author-name">{{ post.author }}</div>
                        <div class="post-date">{{ formatDate(post.date) }}</div>
                    </div>
                </div>

                <h3 class="post-title">{{ post.title }}</h3>

                <div class="post-summary">
                    {{ post.summary || '暂无内容摘要' }}
                </div>

                <div class="card-footer">
                    <el-tag type="info" effect="dark" class="comment-tag">
                        <i class="el-icon-chat-dot-round"></i>
                        {{ post.commentCount || 0 }}
                    </el-tag>
                    <el-button @click="viewPost(post.id)" type="text" class="detail-btn">
                        查看详情 <i class="el-icon-arrow-right"></i>
                    </el-button>
                </div>
            </el-card>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
            <el-pagination background :page-sizes="[12, 24, 36, 48]" :page-size="pageSize" :current-page="pageNum"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="sizeChange"
                @current-change="curPage" class="custom-pagination" />
        </div>

        <!-- 帖子详情弹窗 -->
        <el-dialog :visible.sync="showDialog" fullscreen class="post-detail-modal">
            <div v-if="postDetails" class="modal-content">
                <!-- 主内容区 -->
                <div class="main-content">
                    <!-- 标题区 -->
                    <div class="post-header">
                        <h1 class="post-title">{{ postDetails.title }}</h1>
                        <div class="author-info">
                            <el-avatar :size="48"
                                :src="postDetails.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
                            <div class="meta-info">
                                <div class="author-name">{{ postDetails.author }}</div>
                                <div class="post-time">
                                    发布于 {{ formatDate(postDetails.date) }}
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 内容区 -->
                    <div class="content-box">
                        <div class="post-content">
                            {{ postDetails.neirong }}
                        </div>
                    </div>

                    <!-- 评论区 -->
                    <div class="comment-section">
                        <h3 class="section-title">
                            <i class="el-icon-chat-line-round"></i>
                            评论区（{{ postDetails.comments?.length || 0 }}条）
                        </h3>

                        <!-- 评论列表 -->
                        <div class="comment-list">
                            <div v-for="(comment, index) in postDetails.comments" :key="index" class="comment-item">
                                <el-avatar :size="36"
                                    :src="comment.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
                                    class="comment-avatar" />
                                <div class="comment-content">
                                    <div class="comment-header">
                                        <span class="author">{{ comment.author }}</span>
                                        <span class="time">{{ formatDate(comment.time) }}</span>
                                    </div>
                                    <div class="comment-text">{{ comment.content }}</div>
                                </div>
                            </div>
                        </div>

                        <!-- 评论输入框 -->
                        <div class="comment-editor">
                            <el-input type="textarea" :rows="4" v-model="newComment" placeholder="写下你的精彩评论..."
                                resize="none" class="editor-input" />
                            <div class="editor-actions">
                                <el-button type="primary" size="large" class="submit-btn" @click="submitComment">
                                    发表评论
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 发帖弹窗 -->
        <el-dialog title="发布新帖" :visible.sync="showPostDialog" width="800px" class="create-post-modal">
            <el-form :model="newPost" label-width="80px">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="newPost.title" placeholder="请输入吸引人的标题" size="large" />
                </el-form-item>

                <el-form-item label="摘要" prop="summary">
                    <el-input v-model="newPost.summary" placeholder="请输入内容摘要（最多100字）" type="textarea" :rows="3" />
                </el-form-item>

                <el-form-item label="内容" prop="neirong">
                    <el-input type="textarea" v-model="newPost.neirong" placeholder="请输入详细内容" :rows="8" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="showPostDialog = false">取消</el-button>
                <el-button type="primary" @click="submitPost" class="submit-post-btn">
                    立即发布
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            pageSize: 10,
            pageNum: 1,
            total: 0,

            posts: [],
            param: {},
            showDialog: false,
            postDetails: null,

            showPostDialog: false,
            newPost: {
                title: '',
                summary: '',
                neirong: ''
            },

            // 新增评论相关数据
            newComment: '',
            currentPostId: null
        };
    },
    methods: {
        viewPost(postId) {
            this.showDialog = true;
            this.currentPostId = postId;

            // 初始化postDetails对象
            this.postDetails = {
                comments: [] // 确保comments数组存在
            };

            // 获取帖子详情
            this.$axios.get('api/posts/viewPost/' + postId)
                .then(response => {
                    if (response.data.code == 200) {
                        // 使用Vue.set或Object.assign确保响应式更新
                        this.postDetails = Object.assign({}, response.data.data, {
                            comments: this.postDetails.comments
                        });
                        // 加载评论
                        this.loadComments(postId);
                    }
                });
        },

        // 提交评论方法
        submitComment() {
            if (!this.newComment) {
                this.$message.warning('请输入评论内容');
                return;
            }

            this.$axios.post('api/posts/add', {
                postId: this.currentPostId,
                content: this.newComment
            }).then(res => {
                if (res.data.code === 200) {
                    this.$message.success('评论成功');
                    this.newComment = '';
                    // 重新加载评论
                    this.viewPost(this.currentPostId);
                }
            }).catch(err => {
                this.$message.error('评论失败');
                console.error(err);
            });
        },


        // 加载评论
        loadComments(postId) {
            this.$axios.get('api/posts/list', { // 注意修改为正确的API路径
                params: { postId: postId }
            }).then(response => {
                if (response.data.code === 200) {
                    // 使用Vue.set或直接赋值给已存在的响应式属性
                    this.$set(this.postDetails, 'comments', response.data.data || []);
                }
            }).catch(error => {
                console.error("获取评论失败", error);
            });
        },

        loadPosts() {
            let pageParam = {};
            pageParam.pageNum = this.pageNum;
            pageParam.pageSize = this.pageSize;
            pageParam.param = this.param;
            this.$axios.post('api/posts/queryPosts', pageParam)
                .then(resp => {
                    if (resp.data.code == 200) {
                        this.posts = resp.data.data.list;
                        this.total = resp.data.data.total;
                    }
                })
        },

        formatDate(date) {
            if (!date) return '';
            const d = new Date(date);
            return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
        },

        openPostDialog() {
            this.showPostDialog = true;
        },

        submitPost() {
            this.$axios.post('api/posts/addPosts', this.newPost)
                .then(response => {
                    if (response.data.code == 200) {
                        this.$message.success('等待审核');
                        this.loadPosts();
                        this.showPostDialog = false;
                        // 清空表单
                        this.newPost = {
                            title: '',
                            summary: '',
                            neirong: ''
                        };
                    } else {
                        this.$message.error('发帖失败');
                    }
                })
                .catch(error => {
                    console.error("发帖失败", error);
                    this.$message.error('发帖失败');
                });
        },


        prePage() {
            if (this.pageNum > 1) {
                this.pageNum--;
                this.loadPosts();
            }
        },

        nextPage() {
            if (this.pageNum < Math.ceil(this.total / this.pageSize)) {
                this.pageNum++;
                this.loadPosts();
            }
        },

        curPage(pageNum) {
            this.pageNum = pageNum;
            this.loadPosts();
        },

        sizeChange(pageSize) {
            this.pageSize = pageSize;
            this.pageNum = 1;
            this.loadPosts();
        },
    },

    created() {
        this.loadPosts();
    },
};
</script>

<style scoped>
/* 全局样式重置 */
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

/* 主容器 */
.forum-container {
    min-height: 100vh;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    padding: 2rem;
}

/* 头部操作栏 */
.forum-header {
    display: flex;
    gap: 1.5rem;
    align-items: center;
    margin-bottom: 2rem;
    padding: 1rem;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.search-container {
    flex: 1;
}

.search-input.el-input {
    border-radius: 8px;
    overflow: hidden;
}

.search-input .el-input__inner {
    padding: 1rem 1.5rem;
    font-size: 1rem;
}

.search-btn {
    height: 100%;
    padding: 0 1.5rem;
    border-radius: 0 8px 8px 0;
}

.create-btn {
    padding: 1rem 2rem;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.create-btn i {
    margin-right: 0.5rem;
}

/* 帖子网格布局 */
.post-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

/* 帖子卡片样式 */
.post-card {
    border-radius: 12px;
    border: none;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    background: white;
}

.post-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.card-header {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1rem;
}

.user-avatar {
    flex-shrink: 0;
}

.post-meta {
    line-height: 1.4;
}

.author-name {
    font-weight: 600;
    color: #2d3436;
}

.post-date {
    font-size: 0.875rem;
    color: #636e72;
}

.post-title {
    font-size: 1.25rem;
    color: #2d3436;
    margin-bottom: 1rem;
    line-height: 1.4;
}

.post-summary {
    color: #636e72;
    font-size: 0.95rem;
    line-height: 1.6;
    margin-bottom: 1.5rem;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 1rem;
    border-top: 1px solid #f1f3f5;
}

.comment-tag {
    border-radius: 6px;
    padding: 0.25rem 0.75rem;
}

.detail-btn {
    color: var(--el-color-primary);
    padding: 0.5rem;
}

/* 分页样式 */
.pagination-wrapper {
    margin-top: 2rem;
    display: flex;
    justify-content: center;
}

.custom-pagination .btn-prev,
.custom-pagination .btn-next {
    border-radius: 8px;
}

/* 帖子详情模态框 */
.post-detail-modal {
    border-radius: 16px;
    overflow: hidden;
}

.post-detail-modal .el-dialog__header {
    display: none;
}

.modal-content {
    height: 100vh;
    padding: 2rem;
    background: #f8f9fa;
}

.main-content {
    max-width: 1200px;
    margin: 0 auto;
    background: white;
    border-radius: 16px;
    padding: 2rem;
}

.post-header {
    margin-bottom: 2rem;
}

.post-title {
    font-size: 2rem;
    color: #2d3436;
    margin-bottom: 1.5rem;
}

.author-info {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 2rem;
}

.meta-info {
    line-height: 1.4;
}

.post-time {
    color: #636e72;
    font-size: 0.9rem;
}

.content-box {
    padding: 2rem;
    background: #f8f9fa;
    border-radius: 12px;
    margin-bottom: 2rem;
}

.post-content {
    font-size: 1.1rem;
    line-height: 1.8;
    color: #2d3436;
    white-space: pre-wrap;
}

/* 评论区样式 */
.comment-section {
    padding: 2rem;
    background: white;
    border-radius: 12px;
}

.section-title {
    font-size: 1.5rem;
    color: #2d3436;
    margin-bottom: 1.5rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.comment-list {
    margin-bottom: 2rem;
}

.comment-item {
    display: flex;
    gap: 1rem;
    padding: 1.5rem 0;
    border-bottom: 1px solid #f1f3f5;
}

.comment-item:last-child {
    border-bottom: none;
}

.comment-avatar {
    flex-shrink: 0;
}

.comment-content {
    flex: 1;
}

.comment-header {
    margin-bottom: 0.5rem;
    display: flex;
    align-items: center;
    gap: 1rem;
}

.comment-header .author {
    font-weight: 500;
    color: #2d3436;
}

.comment-header .time {
    color: #636e72;
    font-size: 0.875rem;
}

.comment-text {
    color: #2d3436;
    line-height: 1.6;
}

/* 评论编辑器 */
.comment-editor {
    margin-top: 2rem;
}

.editor-input textarea {
    border-radius: 8px;
    padding: 1rem;
    font-size: 1rem;
}

.editor-actions {
    margin-top: 1rem;
    display: flex;
    justify-content: flex-end;
}

.submit-btn {
    padding: 0.75rem 2rem;
    border-radius: 8px;
    font-weight: 500;
}

/* 发帖模态框 */
.create-post-modal .el-dialog__header {
    border-bottom: 1px solid #f1f3f5;
    padding: 1.5rem;
}

.create-post-modal .el-dialog__body {
    padding: 1.5rem;
}

.submit-post-btn {
    padding: 0.75rem 2rem;
    border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .forum-header {
        flex-direction: column;
        align-items: stretch;
    }

    .post-grid {
        grid-template-columns: 1fr;
    }

    .post-detail-modal .main-content {
        padding: 1rem;
    }

    .post-title {
        font-size: 1.5rem;
    }
}
</style>